from exts import db
from common import constant
from common.base_model import BaseModel, BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin

MIDDLE_DB_STR_LEN = constant.MIDDLE_DB_STR_LEN
LONG_DB_STR_LEN = constant.LONG_DB_STR_LEN
COMMON_DECIMAL = constant.COMMON_DECIMAL


class Sku(db.Model, BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
    __tablename__ = 'sku'

    id = db.Column(db.Integer, primary_key=True)
    spu_id = db.Column(db.Integer, db.ForeignKey('spu.id'))
    sku_sn = db.Column(db.String(MIDDLE_DB_STR_LEN), nullable=False)  # 货号
    spec_attr_ele = db.Column(db.JSON)
    warning_number_low = db.Column(db.DECIMAL(20, COMMON_DECIMAL), default=0)
    warning_number_high = db.Column(db.DECIMAL(20, COMMON_DECIMAL), default=0)
    barcode = db.Column(db.String(MIDDLE_DB_STR_LEN))  # 条形码

    # 级联删除关系 backref='sku',
    sku_unit_prices = db.relationship('SkuToUnit', cascade="all, delete-orphan")

    # spu = db.relationship('Spu', foreign_keys='Sku.spu_id')
    # 公司+货号 不可重复
    __table_args__ = (
        db.UniqueConstraint('sku_sn', 'company_id'),
    )


# 商品与单位1对多
class SkuToUnit(db.Model, BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
    __tablename__ = 'sku_to_unit'

    id = db.Column(db.Integer, primary_key=True)
    sku_id = db.Column(db.Integer, db.ForeignKey('sku.id'))
    unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'))
    purchase_price = db.Column(db.DECIMAL(20, COMMON_DECIMAL), default=0)
    sale_price = db.Column(db.DECIMAL(20, COMMON_DECIMAL), default=0)

    sku = db.relationship('Sku', foreign_keys='SkuToUnit.sku_id')
    unit = db.relationship('Unit', foreign_keys='SkuToUnit.unit_id')

    # sku = db.relationship('Sku', backref='sku_to_unit')
    # sell_price_backup = db.Column(db.DECIMAL(20, COMMON_DECIMAL), default=0,
    #                               server_default='0')  # 预设售价（备份）, 用于记录以前的售价


# # 单品图片
# class SpuToFile(db.Model, BasicModelMixin, CompanyMixin, CreateMixin, UpdateMixin, DeleteMixin):
#     __tablename__ = 'sku_to_file'
#
#     sku_id = db.Column(db.Integer, db.ForeignKey('sku.id'), primary_key=True)
#     file_id = db.Column(db.Integer, db.ForeignKey('file.id'), primary_key=True)

"""规格json
    >>> {
        '机身颜色'：'香槟金'，
        '内存'：'16G'
    }
    """
# own_spec = db.Column(db.JSON)